extends layout

block content
	.index-page
		img.logo(src='/images/logo.png')
		.input-group.diff
			p COLOR DIFFERENCE TOLERANCE
			input#diffTolerance(value='30')
		.images
			each val in images
				//a(href='photo/#{val.substring(16)}')
				a.thumbnail-wrapper
					img.thumbnail(src='#{val}')
		.photo-overlay
			span.close-icon &#xd7;
			canvas#mainImage
			button.get-qr-button 发给我图片 / Save Photo
			.bg-images
				//.bg-image.city
				span.bg-image.beach
				span.bg-image.mountains
				span.bg-image.shanghai
				span.bg-image.stadium
				.clearfix
			.clearfix

		.qr-modal
			.header
				h2.title Please Scan the QR Code to View Your Results
				span.close-modal#closeModal &#x2715;
			.body#qrModalBody
		script(src='/javascripts/jquery.min.js')

		script.
			console.log('inline script is loaded');

			var photoid;

			$('.photo-overlay .close-icon').on('click', function(){
				//$('.photo-overlay').removeClass('active');
				console.log('hello')
				$('.photo-overlay').animate({opacity: 0}, 300, function(){
					$('.photo-overlay').css({'display': 'none', 'z-index': -1})
				});
				$('.bg-images').animate({opacity: 0}, 300);
				var canvas = document.getElementById('mainImage');
				var ctx = canvas.getContext('2d');
				setTimeout(function(){ctx.clearRect(0, 0, canvas.width, canvas.height)},400);
			})
			
			$('.thumbnail-wrapper').on('click', function(){
				console.log($(this)[0].baseURI)
				console.log($(this).find('.thumbnail').attr('src'))

				var thumbnailWidth = $(this).find('.thumbnail').width();
				var thumbnailHeight = $(this).find('.thumbnail').height();

				//ui interactions to get canvas and background images display
				if ( !$('.photo-overlay').hasClass('active') ){
					//$('.photo-overlay').addClass('active')
					$('.photo-overlay').css({'display': 'block', 'z-index': 1});
					$('.photo-overlay').animate({opacity: 1}, 300);
					$('.bg-images').animate({opacity: 1}, 300);
				}
					//} else {
					//	$('.photo-overlay').removeClass('active')
					//}
				//load up canvas with image
				var img = new Image();
			
				img.onload = function(){
					var canvas = document.getElementById('mainImage');
					var ctx = canvas.getContext('2d');
					canvas.width = thumbnailWidth * 4;
					canvas.height = thumbnailHeight * 4;
					ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, thumbnailWidth * 4, thumbnailHeight * 4)

					//get image data and store in array
					var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
					var data = imageData.data;

					//convert image data to xyz values
					//var xyzImageData = rgbToXyz(red, green, blue)
					var start = [data[0], data[1], data[2]];
					
					//function to convert one point of data from rgb to xyz
					var rgbToXyz = function(pixelDataArray){
						var temp_r = parseFloat(pixelDataArray[0] / 255);
						var temp_g = parseFloat(pixelDataArray[1] / 255);
						var temp_b = parseFloat(pixelDataArray[2] / 255);

						if (temp_r > 0.04045) {
							temp_r = Math.pow(( (temp_r + 0.055 ) / 1.055 ), 2.4)
						} else {
							temp_r = temp_r / 12.92
						}
						if (temp_g > 0.04045) {
							temp_g = Math.pow(( (temp_g + 0.055 ) / 1.055 ), 2.4)
						} else {
							temp_g = temp_g / 12.92
						}
						if (temp_b > 0.04045) {
							temp_b = Math.pow(( (temp_b + 0.055 ) / 1.055 ), 2.4)
						} else {
							temp_b = temp_b / 12.92
						}

						temp_r = temp_r * 100;
						temp_g = temp_g * 100;
						temp_b = temp_b * 100;

						var x = temp_r * 0.4124 + temp_g * 0.3576 + temp_b * 0.1805;
						var y = temp_r * 0.2126 + temp_g * 0.7152 + temp_b * 0.0722;
						var z = temp_r * 0.0193 + temp_g * 0.1192 + temp_b * 0.9505;

						return xyzToLab([x,y,z]);
					}

					var xyzToLab = function(xyzPixelDataArray){
						var ref_x =  95.047;
						var ref_y = 100.000;
						var ref_z = 108.883;
						
						temp_x = xyzPixelDataArray[0] / ref_x;
						temp_y = xyzPixelDataArray[1] / ref_y;
						temp_z = xyzPixelDataArray[2] / ref_z;

						if ( temp_x > 0.008856 ) {
							temp_x = Math.pow(temp_x, 1/3)
						} else {
							temp_x = ( 7.787 * temp_x ) + ( 16 / 116 )
						}
						if ( temp_y > 0.008856 ) {
							temp_y = Math.pow(temp_y, 1/3)
						} else {
							temp_y = ( 7.787 * temp_y ) + ( 16 / 116 )
						}
						if ( temp_z > 0.008856 ) {
							temp_z = Math.pow(temp_z, 1/3)
						} else {
							temp_z = ( 7.787 * temp_z ) + ( 16 / 116 )
						}

						var cie_l = 116 * temp_y - 16;
						var cie_a = 500 * (temp_x - temp_y);
						var cie_b = 200 * (temp_y - temp_z );

						labVal = [cie_l, cie_a, cie_b, 1];
						return labVal;
					}

					//convert image data to lab values
					var convertToLab = function(){
						var labVals = [];
						console.log(data.length);
						for (var i = 0; i < data.length; i += 4){
							var conversionInput = [data[i], data[i+1], data[i+2]];
							var conversionOutput = rgbToXyz(conversionInput);
							for (var j = 0; j < conversionOutput.length; j++){
								labVals.push(conversionOutput[j])
							}
						}
						return labVals
					}

					labVals = convertToLab();
					//console.log(labVals);

					//sample top left pixel, and diff with delta e94 for each pixel
					var labStart = [labVals[0], labVals[1], labVals[2], labVals[3]];
					
					var deltaTolerance = 30;
					deltaTolerance = parseInt(document.getElementById('diffTolerance').value);

					
					for (var k = 0; k < data.length; k += 4){
						var pixelDelta = Math.sqrt( (Math.pow( labStart[0] - labVals[k], 2 )) + (Math.pow( labStart[1] - labVals[k+1], 2 )) +  (Math.pow( labStart[2] - labVals[k+2], 2 )) )
						if (k == data.length / 4) {
							console.log(pixelDelta)
						}
					

						if ( pixelDelta < deltaTolerance ){
							data[k+3] = 0
						}
						
					}
					
					//canvas.setAttribute('style', 'width: ' + thumbnailWidth);
					//canvas.setAttribute('style', 'height: ' + thumbnailHeight);
					
					ctx.putImageData(imageData, 0, 0);
					//upload filtered image
					uploadFilteredImage(canvas, ctx);
					//get image and rewrite canvas
				}

				
				img.src = '..' + $(this).find('.thumbnail').attr('src');
				photoid = $(this).find('.thumbnail').attr('src').substr(16);
			
			})

			

			var uploadFilteredImage = function(canvas, ctx){
				$.ajax({
					type: 'POST',
					//this is for the new version
					url: '../photo/transparent/'+photoid,
					//this is for the old version
					//url: '../photo/transparent/#{photoid}',
					data: {
						imgBase64: canvas.toDataURL("image/jpg")
					}
				}).done(function(res){
					console.log('transparent file uploaded');
					console.log(res)
					redrawWithNewImage(canvas, ctx, res)
				})

				/*
				//usingo xmlhttprequest
				var image = canvas.toDataURL("image/png")
				//make request
				var xmlhttp = new XMLHttpRequest();
				xmlhttp.open("POST", '/photo/transparent/#{photoid}', true);
				xmlhttp.setRequestHeader('Content-Type', 'application/blob; charset=UTF-8');
				xmlhttp.send('data='+image);
				*/
			}
			
			var redrawWithNewImage = function(canvas, ctx, newImage){
				console.log('executing redrawwithnewimage');
				console.log(newImage);
				var img = new Image();
				img.src = newImage;
				var canvas = document.getElementById('mainImage');
				var ctx = canvas.getContext('2d');
				console.log('new image');
				console.log(newImage);
				ctx.drawImage(img, 0, 0, img.width, img.height);
			}

			$('.bg-image').click(function(){
				
				//this is for development
				var newImgSrc = $(this).css('background-image').replace('url("http://localhost:3000', '..').slice(0,-2);
				
				//this is for production
				//var newImgSrc = $(this).css('background-image').replace('url("http://greenscreen.shanghaiappmaker.com', '..').slice(0,-2);

				var canvas = document.getElementById('mainImage');
				var ctx = canvas.getContext('2d');
				img = new Image();
				img.src = newImgSrc;
				ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

				var transImage = '/images/trans/' + photoid;

				redrawWithNewImage(canvas, ctx, transImage);
			})


			//apply other backgrounds to the canvas
			//this went into the custom.js file because I'm lazy and wanted to use jquery


			//export image from canvas
			//also in custom.js

			//send new image back to server and generate qr code